<template>
  <div class="app-container">
    <!-- 导航区域 -->
    <NavBarBread :bread="[$route.meta.parentName, $route.meta.menuName]">
      <el-tooltip class="item" effect="dark" content="导出" placement="top-end">
        <i class="el-icon-sold-out" style="font-size: 20px; color: #05A7aB;" @click="handelExport" />
      </el-tooltip>
    </NavBarBread>
    <!-- 搜索条件区域 -->
    <div class="serach-container">
      <div class="search-inputs">
        <el-form :inline="true" :model="simpleForm" class="demo-form-inline searchCondition" label-position="right" label-width="100px">
          <el-form-item label="VIN">
            <el-input v-model="simpleForm.vin" maxlength="17" placeholder="请输入VIN码" />
          </el-form-item>
          <el-form-item label="品牌名称">
            <el-select v-model="simpleForm.brandName" clearable placeholder="请选择品牌名称">
              <el-option v-for="item in brandOptions" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item label="车系名称">
            <el-select v-model="simpleForm.seriesName" filterable clearable placeholder="请选择车系">
              <el-option v-for="item in seriesOptions" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-button type="primary" @click="queryTableList">查询</el-button>
          <el-button @click="handelRest">重置</el-button>
        </el-form>
        <el-collapse-transition>
          <div v-if="isMore" class="more-container">
            <el-form :inline="true" :model="complexForm" class="demo-form-inline searchCondition" label-position="right" label-width="100px">
              <el-form-item label="车型名称">
                <el-select v-model="complexForm.modelName" filterable clearable placeholder="请选择车型">
                  <el-option v-for="item in modelOptions" :key="item" :label="item" :value="item" />
                </el-select>
              </el-form-item>
              <el-form-item label="申诉提交日期">
                <el-date-picker v-model="appealCommitDate" type="daterange" clearable range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
              </el-form-item>
              <el-form-item label="是否出行">
                <el-select v-model="complexForm.isTravel" clearable placeholder="请选择是否出行">
                  <el-option label="是" :value="0" />
                  <el-option label="否" :value="1" />
                </el-select>
              </el-form-item>
            </el-form>
            <el-form :inline="true" class="demo-form-inline searchCondition" label-position="right" label-width="100px">
              <el-form-item label="是否跨大区">
                <el-select v-model="complexForm.isCrossRegion" clearable placeholder="请选择报备类型">
                  <el-option label="是" :value="1" />
                  <el-option label="否" :value="0" />
                </el-select>
              </el-form-item>
              <el-form-item label="申诉状态">
                <el-select v-model="complexForm.auditStatus" clearable placeholder="请选择报备状态">
                  <el-option v-for="(item, key) in auditStatusMap" :key="key" :label="auditStatusMap[key]" :value="key" />
                </el-select>
              </el-form-item>
              <el-form-item label="购车人姓名">
                <el-input v-model="simpleForm.customerName" maxlength="17" placeholder="请输入购车人姓名" />
              </el-form-item>
            </el-form>
          </div>
        </el-collapse-transition>
      </div>
      <div class="search-toggle">
        <el-button
          type="text"
          @click="handelToggle"
        >
          {{ isMore ? '普通搜索' : '高级搜索' }}
        </el-button>
      </div>
    </div>
    <!-- 主内容区域 -->
    <div class="section-container">
      <el-table v-loading="listLoading" size="mini" :data="tables.data" border fit highlight-current-row style="width: 100%" height="600">
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column v-for="item in tables.columns" :key="item.key" :width="item.width" :label="item.lable" :align="item.align" :show-overflow-tooltip="true">
          <template slot-scope="{row}">
            <span v-if="item.key === 'vehicleNature'">{{ row[item.key] ? vehicleNatureMap[row.vehicleNature] : '' }}</span>
            <span v-else>{{ row[item.key] }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="100" fixed="right">
          <template slot-scope="{row}">
            <el-button
              type="text"
              size="small"
              @click="handelCheckDetail(row)"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination :total="total" :page.sync="pages.page" :limit.sync="pages.limit" @pagination="changePages" />
    </div>
    <!-- 详情弹窗 -->
    <el-dialog title="详情" :visible.sync="detailVisible" width="80%">
      <el-collapse>
        <el-collapse-item title="车辆报备信息">
          <div class="detailContainer">
            <div v-for="item in tables.columns" :key="item.key" class="detailItem">
              <div>
                <span class="detailTitle">{{ item.lable }}：</span>
                <span class="detailContent" v-if="item.key === 'vehicleNature'">{{detailData[item.key] ? vehicleNatureMap[detailData.vehicleNature] : '' }}</span>
                <span class="detailContent" v-else>{{ detailData[item.key] }}</span>
              </div>
            </div>
          </div>
          <div class="reseson">
            <span class="detailTitle">申请原因：</span>
            <span class="detailContent">{{ detailData.reason }}</span>
          </div>
        </el-collapse-item>
        <el-collapse-item title="附件信息">
          <el-tabs v-model="activeTabs" type="border-card" @tab-click="changeTabs">
            <!-- 车辆性质为政企 -->
            <el-tab-pane v-if="detailData.vehicleNature == 84191003" label="营业执照/资质证明" name="0">
              <div v-loading="tabsLoading" class="files-container">
                <div v-for="(item, index) in licenseList.data" :key="index" class="files-item">
                  <video v-if="item.type === 'video'" style="width: 100%; height: 100%;" controls="controls" preload="auto">
                    <source :src="item.src"  type="video/mp4">
                  </video>
                  <el-image v-else-if="item.type==='img'" :src="item.src" :preview-src-list="licenseList.preview" style="width: 100%; height: 100%;" />
                  <div v-else @click="previewPdf(item.src)">
                    <pdf :src="item.src"></pdf>
                  </div>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane v-if="detailData.vehicleNature == 84191003" label="DMS”经销商大客户报备“载图" name="1">
              <div v-loading="tabsLoading" class="files-container">
                <div v-for="(item, index) in screenshotList.data" :key="index" class="files-item">
                  <video v-if="item.type === 'video'" style="width: 100%; height: 100%;" controls="controls" preload="auto">
                    <source :src="item.src"  type="video/mp4">
                  </video>
                  <el-image v-else-if="item.type==='img'" :src="item.src" :preview-src-list="screenshotList.preview" style="width: 100%; height: 100%;" />
                  <div v-else @click="previewPdf(item.src)">
                    <pdf :src="item.src"></pdf>
                  </div>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane v-if="detailData.vehicleNature != 84191003" label="身份证" name="0">
              <div v-loading="tabsLoading" class="files-container">
                <div v-for="(item, index) in idCardList.data" :key="index" class="files-item">
                  <video v-if="item.type === 'video'" style="width: 100%; height: 100%;" controls="controls" preload="auto">
                    <source :src="item"  type="video/mp4">
                  </video>
                  <el-image v-else-if="item.type==='img'" :src="item.src" :preview-src-list="idCardList.preview" style="width: 100%; height: 100%;" />
                  <div v-else @click="previewPdf(item.src)">
                    <pdf :src="item.src"></pdf>
                  </div>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane v-if="detailData.vehicleNature != 84191003" label="人车合影" name="1">
              <div v-loading="tabsLoading" class="files-container">
                <div v-for="(item, index) in groupPhotoList.data" :key="index" class="files-item">
                  <video v-if="item.type === 'video'" style="width: 100%; height: 100%;" controls="controls" preload="auto">
                    <source :src="item.src"  type="video/mp4">
                  </video>
                  <el-image v-else-if="item.type==='img'" :src="item.src" :preview-src-list="groupPhotoList.preview" style="width: 100%; height: 100%;" />
                  <div v-else @click="previewPdf(item.src)">
                    <pdf :src="item.src"></pdf>
                  </div>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="发票" name="2">
              <div v-loading="tabsLoading" class="files-container">
                <div v-for="(item, index) in invoiceList.data" :key="index" class="files-item">
                  <video v-if="item.type === 'video'" style="width: 100%; height: 100%;" controls="controls" preload="auto" >
                    <source :src="item.src"  type="video/mp4">
                  </video>
                  <el-image v-else-if="item.type === 'img'" :src="item.src" :preview-src-list="invoiceList.preview" style="width: 100%; height: 100%;" />
                  <div v-else @click="previewPdf(item.src)">
                    <pdf :src="item.src"></pdf>
                  </div>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="行驶证" name="3">
              <div v-loading="tabsLoading" class="files-container">
                <div v-for="(item, index) in vehicleLicenseList.data" :key="index" class="files-item">
                  <div v-if="item.type === 'video'">
                    <video style="width: 100%; height: 100%;" controls="controls" preload="auto">
                      <source :src="item.src"  type="video/mp4">
                    </video>
                  </div>
                  <div v-else-if="item.type ==='img'">
                    <el-image :src="item.src" :preview-src-list="vehicleLicenseList.preview" style="width: 100%; height: 100%;" />
                  </div>
                  <div v-else @click="previewPdf(item.src)">
                    <pdf :src="item.src"></pdf>
                  </div>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="其他" name="4">
              <div v-loading="tabsLoading" class="files-container">
                <div v-for="(item, index) in otherList.data" :key="index" class="files-item">
                  <div v-if="item.type === 'video'">
                    <video style="width: 100%; height: 100%;" controls="controls" preload="auto">
                      <source :src="item.src"  type="video/mp4">
                    </video>
                  </div>
                  <div v-else-if="item.type ==='img'">
                    <el-image :src="item.src" :preview-src-list="otherList.preview" style="width: 100%; height: 100%;" />
                  </div>
                  <div v-else @click="previewPdf(item.src)">
                    <pdf :src="item.src"></pdf>
                  </div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-collapse-item>
        <el-collapse-item title="审批记录明细">
          <div class="section">
            <el-table v-loading="recordsDetails.listLoading" size="mini" :data="recordsDetails.tables.data" border fit highlight-current-row style="width: 100%" height="240">
              <el-table-column type="index" label="序号" width="50" align="center" />
              <el-table-column v-for="item in recordsDetails.tables.columns" :key="item.key" :label="item.lable" :align="item.align" :show-overflow-tooltip="true">
                <template slot-scope="{row}">
                  <span>{{ row[item.key] }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-collapse-item>
      </el-collapse>
    </el-dialog>
    <!-- 预览pdf -->
    <el-dialog title="预览" :visible.sync="previewVisible" width="80%">
      <!-- <pdf style="width: 100%; height: 100%;" :src="pdfUrl"></pdf> -->
      <pdf v-for="currentPage in pdfPages" :key="currentPage" :src="pdfUrl" :page="currentPage" class="preview-pdf mb-3" @loaded="loadPdfHandler"></pdf>
    </el-dialog>
  </div>
</template>

<script>
import { appealInfoExport, queryAppealPage, queryAppealSelectOptions, queryAppealFileInfo, queryAppealFiles, queryAppealProcessInfo } from '@/api/crossRegionalMonitoring'
import Pagination from '@/components/Pagination'
import NavBarBread from '@/components/NavBarBread'
import { exportExcelByBlob } from '@/utils/public'
import { dateFtt } from '@/utils/public'
import pdf from "vue-pdf"
// 审批结果数据字典
const auditStatusMap = {
  84161001: '未提交',
  84161002: '流程审批中',
  84161003: '审批驳回',
  84161004: '审批拒绝',
  84161005: '审批通过'
}
// 车辆性质数据字典
const vehicleNatureMap = {
  '84191001': '零售',
  '84191002': '出行',
  '84191003': '政企'
}
export default {
  name: 'AppealManage',
  components: { Pagination, NavBarBread, pdf },
  data() {
    return {
      auditStatusMap,
      vehicleNatureMap,
      tables: {
        columns: [
          { lable: 'VIN', key: 'vin', width: '180px', align: 'center' },
          { lable: '大区', key: 'salesArea', width: '100px', align: 'center' },
          { lable: '省份', key: 'provinceName', width: '80px', align: 'center' },
          { lable: '城市', key: 'cityName', width: '80px', align: 'center' },
          { lable: '店简称', key: 'dealerName', width: '100px', align: 'center' },
          { lable: '店代码', key: 'dealerCode', width: '80px', align: 'center' },
          { lable: '品牌', key: 'brandName', width: '180px', align: 'center' },
          { lable: '车系', key: 'seriesName', width: '120px', align: 'center' },
          { lable: '车型', key: 'modelName', width: '160px', align: 'center' },
          { lable: '车辆性质', key: 'vehicleNature', width: '100px', align: 'center' },
          { lable: '是否出行', key: 'isTravel', width: '80px', align: 'center' },
          { lable: '是否跨大区', key: 'isCrossRegion', width: '90px', align: 'center' },
          { lable: '提交申诉日', key: 'appealCommitTime', width: '160px', align: 'center' },
          { lable: '申诉状态', key: 'auditStatusName', width: '100px', align: 'center' },
          { lable: '审核角色', key: 'auditRole', width: '80px', align: 'center' },
          { lable: '审核原因', key: 'auditDesc', width: '100px', align: 'center' },
          { lable: '开票日期', key: 'invoiceString', width: '160px', align: 'center' },
          { lable: '上牌日期', key: 'registerString', width: '180px', align: 'center' },
          { lable: '购车人姓名', key: 'customerName', width: '100px', align: 'center' },
          { lable: '上牌大区', key: 'areaName', width: '80px', align: 'center' },
          { lable: '上牌省份', key: 'licenseProvinceName', width: '80px', align: 'center' },
          { lable: '上牌城市', key: 'licenseCityName', width: '80px', align: 'center' },
          { lable: '允许上牌时间', key: 'registerStartString', width: '160px', align: 'center' },
          { lable: '允许上牌结束时间', key: 'registerEndString', width: '160px', align: 'center' }
        ],
        data: []
      },
      pages: {
        pageNum: 1,
        pageSize: 20
      },
      total: 0,
      listLoading: true,
      detailVisible: false,
      detailData: {},
      simpleForm: {},
      complexForm: {},
      appealCommitDate: [],
      isMore: false,
      brandOptions: [],
      modelOptions: [],
      seriesOptions: [],
      // 附件相关
      tabsLoading: false,
      groupPhotoList: { // 人车合影照片/视频
        data: [],
        preview: []
      },
      idCardList: { // 身份证/营业执照
        data: [],
        preview: []
      },
      invoiceList: { // 发票
        data: [],
        preview: []
      },
      licenseList: { // 营业执照/资质证明
        data: [],
        preview: []
      },
      otherList: { // 其他附件
        data: [],
        preview: []
      },
      screenshotList: { // DMS“经销商大客户报备”截图
        data: [],
        preview: []
      },
      vehicleLicenseList: { // 行驶证
        data: [],
        preview: []
      },
      activeTabs: '0',
      // 审批记录相关
      recordsDetails: {
        pages: {
          pageNum: 1,
          pageSize: 20
        },
        tables: {
          columns: [
            { lable: '审批人', key: 'approveName', width: '160px', align: 'center' },
            { lable: '审批意见', key: 'approveOpinion', width: '180px', align: 'center' },
            { lable: '审批情况 ', key: 'approveStatus', width: '100px', align: 'center' },
            { lable: '审批时间', key: 'createdAt', width: '80px', align: 'center' }
          ],
          data: []
        },
        total: 0,
        listLoading: true
      },
      previewVisible: false,
      pdfUrl: '',
      pdfPages: 1,
      currentPage: 1
    }
  },
  created() {
    this.queryOptions()
    this.queryTableList()
  },
  methods: {
    changePages(params) {
      this.pages = { ...params }
      this.queryTableList()
    },
    async queryOptions() {
      const { data } = await queryAppealSelectOptions()
      const item = data.data
      const { reportBrandNames, reportModelNames, reportSeriesNames } = item
      this.brandOptions = reportBrandNames
      this.modelOptions = reportModelNames
      this.seriesOptions = reportSeriesNames
    },
    async queryTableList() {
      this.listLoading = true
      const { data } = await queryAppealPage(this.formatParams())
      const items = data.data
      this.tables.data = items.list
      this.total = items.total
      this.listLoading = false
    },
    formatParams() {
      const params = { ...this.simpleForm, ...this.complexForm, ...this.pages }
      if (this.appealCommitDate && this.appealCommitDate.length) {
        params['appealCommitTimeStart'] = dateFtt(this.appealCommitDate[0])
        params['appealCommitTimeEnd'] = dateFtt(this.appealCommitDate[1], 'yyyy-MM-dd') + ' 23:59:59'
      }
      return params
    },
    // 清空查询条件
    handelRest() {
      for (const key in this.simpleForm) {
        this.simpleForm[key] = ''
      }
      this.clearComplexSearchCondetions()
    },
    // 清空复杂查询条件
    clearComplexSearchCondetions() {
      for (const key in this.complexForm) {
        this.complexForm[key] = ''
      }
      this.appealCommitDate = []
    },
    handelToggle() {
      this.isMore = !this.isMore
      !this.isMore && this.clearComplexSearchCondetions()
    },
    changeTabs() {
      // switch
      // console.log(tab)
    },
     /**
     * 查看详情
     * @appealId 申诉ID
     * @queryAppealFileInfo 查询对应申诉的附件组
     */
    handelCheckDetail(row) {
      this.detailVisible = true
      this.detailData = row
      this.queryAppealProcessTables()
      queryAppealFileInfo({ appealId: row.appealId }).then(res => {
        const { data } = res
        const { idCardList, groupPhotoList, otherList, invoiceList, licenseList, screenshotList, vehicleLicenseList } = data.data
        // 车辆性质为政企
        if (row.vehicleNature == 84191003) {
          this.forEachQueryFiles(licenseList, 'licenseList')
          this.forEachQueryFiles(screenshotList, 'screenshotList')
        } else {
          // 车辆性质为零售/出行  身份证、人车合影照片/视频
          this.forEachQueryFiles(idCardList, 'idCardList')
          this.forEachQueryFiles(groupPhotoList, 'groupPhotoList')
        }
        // 无论何种现象都会展示其他附件\发票、行驶证
        this.forEachQueryFiles(otherList, 'otherList')
        this.forEachQueryFiles(vehicleLicenseList, 'vehicleLicenseList')
        this.forEachQueryFiles(invoiceList, 'invoiceList')
      })
    },
    getFileType(file) {
      const index = file.lastIndexOf('.')
      const fileTypeStr = file.slice(index+1, file.length)
      let fileType = 'img'
      switch(fileTypeStr) {
        case 'mp4':
          fileType = 'video'
          break;
        case 'pdf':
          fileType = 'pdf'
          break;
        default:
          fileType = 'img'
      }
      return fileType
    },
    // 遍历附件组 获取对应的文件流
    forEachQueryFiles(arr, tabs) {
      this[tabs].data = []
      this[tabs].preview = []
      if (arr && arr.length) {
        arr.forEach(item => {
          this.queryAppealFiles(item, tabs)
        })
      }
    },
    async queryAppealProcessTables() {
      this.recordsDetails.listLoading = true
      const { data } = await queryAppealProcessInfo({ appealId: this.detailData.appealId })
      const items = data.data
      this.recordsDetails.tables.data = items
      this.recordsDetails.listLoading = false
    },
    // 读取文件流
    async queryAppealFiles(params, tabs) {
      const fileType = this.getFileType(params.fileName)
      const { data } = await queryAppealFiles(params)
      console.log(data)
      const url = window.URL.createObjectURL(data)
      if(fileType === 'pdf') {
        const pdfUrl = pdf.createLoadingTask({ url })
        this[tabs].data.push({ src: pdfUrl, type: fileType })
      } else {
        this[tabs].data.push({ src: url, type: fileType })
      }
      if (fileType === 'img') {
        this[tabs].preview.push(url)
      }
    },
    previewPdf(pdfUrl){
      this.previewVisible = true
      this.pdfUrl = pdfUrl
      this.loadPdfHandler()
    },
    loadPdfHandler () {
      this.pdfUrl.promise.then(pdf => {
        // 获取pdf文件相关信息，页码等
        this.pdfPages = pdf.numPages
      })
      this.currentPage = 1 // 加载的时候先加载第一页
      // 强制刷新
      this.$forceUpdate()
    },
    handelExport() {
      const params = this.formatParams()
      this.$delete(params, 'pageNum')
      this.$delete(params, 'pageSize')
      appealInfoExport(params).then(res => {
        const { data } = res
        const fileName = `${this.$route.meta.menuName}.xlsx`
        exportExcelByBlob(data, fileName)
      })
    }
  }
}
</script>
<style scoped>
  ::v-deep .el-collapse-item{
      margin-bottom: 5px;
  }
  ::v-deep .el-tabs__item.is-active{
      color: #02a8ac;
  }
  ::v-deep .el-collapse-item__header{
      background-color: #d5d8d8;
      height: 35px;
      line-height: 35px;
      font-weight: 650;
      padding-left: 10px;
  }
 ::v-deep .el-collapse-item__content{
   padding-bottom: 0px;
 }
  ::v-deep .el-image-viewer__close{
    color: #fff;
  }
</style>
<style lang="scss" scoped>
  ::v-deep(.el-form-item .el-form-item__content){
    width: 200px;
  }
  ::v-deep .el-image-viewer__close{
    color: #fff;
  }
  .el-input{
    width: 202px;
  }
  .action-container{
    padding-top: 30px;
    margin-top: 20px;
    border-top: 1px solid gray;
  }
  .serach-container{
    width: 100%;
    display: flex;
    justify-content: space-between;
  }
  .tool-container{
    width: 100%;
    display: flex;
    justify-content: space-between;
    line-height: 40px;
    .toggle-warning{
      font-family: 'PingFangSC-Semibold', 'PingFang SC Semibold', 'PingFang SC', sans-serif;
      font-weight: 650;
      font-style: normal;
      font-size: 16px;
    }
  }
  .reseson{
    display: flex;
    min-height: 50px;
    padding: 0 15px;
    width: 100%;
    .detailTitle{
      font-weight: bold;
      display: inline-block;
      max-width: 120px;
      min-width: 60px;
    }
  }
  .detailContainer {
      display: flex;
      flex-wrap: wrap;
      padding: 0 15px;
      width: 100%;
      max-height: 400px;
      overflow-y: scroll;
      .detailItem{
          width: 33%;
          min-height: 40px;
          div{
              display: flex;
          }
          .detailTitle{
              font-weight: bold;
              display: inline-block;
              max-width: 120px;
              min-width: 60px;
          }
      }
  }
  .files-container{
      width: 100%;
      padding: 0 100px;
      box-sizing: border-box;
      display: flex;
      justify-content: center;
      flex-wrap: wrap;
      .files-item{
        width: 200px;
        height: 150px;
        margin-bottom: 10px;
      }
      .files-item:not(:first-of-type) {
        margin-left: 10px;
      }
  }
</style>
